package com.rtx.express.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.common.HttpUtils;
import com.rtx.common.MD5Helper;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.cfwl.CfwlRequest;
import com.rtx.edi.model.express.cfwl.Mailno;
import com.rtx.edi.model.express.cfwl.MailnoResponse;
import com.rtx.edi.model.express.cfwl.Vipparams;
import com.rtx.edi.model.express.cfwl.Vipreceiver;
import com.rtx.edi.model.express.cfwl.Vipsender;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;

@RtxExpressApi(expressApiName = "春风物流")
@Service("快递接口SPRING56")
public class CFWLExpressAPI implements IExpressService {

	Logger log = LoggerFactory.getLogger(this.getClass());

	/*
	 * /** 处理春风物流请求接口
	 * 
	 * @return
	 */
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task = bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		
		try {
			Vipparams vipparams = coverToCFWLRequest(bo);
			
			log.info("订单-{}-获取春风物流快递请求：{}", task.getExternorderkey(), JSON.toJSONString(vipparams) );
			String vipresult = HttpUtils.sendPostHttp("http://api.spring56.com/port/interface.php", JSON.parseObject(JSON.toJSONString(vipparams), new TypeReference<Map<String, String>>() {})); 
			log.info("订单-{}-获取春风物流快递请求返回：{}", task.getExternorderkey(), vipresult);
//			{"result":"true","error_code":"","keys":"","remark":"操作成功","info":{"mailno":"6004750514"}}
			MailnoResponse reponse = JSONObject.parseObject(vipresult, MailnoResponse.class);
			if ("true".equals("true")) {
				bo.setCallCreateOrderAPIData(vipresult);
				bo.setCallCreateOrderAPIResult("ok");
				PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
				
				result.setWaybillNo(reponse.getInfo().getMailno());
				
				bo.setExpressResult(result);
			}else {
				bo.setCallCreateOrderAPIData(vipresult);
				bo.setMsg(bo.getMsg());
				throw new RuntimeException(reponse.getRemark());
			} 
			
		} catch (Exception e) {
			bo.setCallCreateOrderAPIData(e.getMessage());
			bo.setMsg(bo.getMsg());
			log.info("订单-{}-获取春风物流快递单号失败：{}", task.getExternorderkey(), e);
		}
	}

	
	private Vipparams coverToCFWLVIPRequest(ExpressBO bo) {
		Vipparams vipparams = new Vipparams();
		PlExpressApi  task = bo.getExpressTask();
		CfwlRequest request = new CfwlRequest();
		request.setId(task.getExternorderkey());
		request.setType("simple");
		request.setQuantity(1);
		request.setMailno(bo.getCallCreateOrderAPIData());
		request.setBulk("0");
		request.setRemark("0");
		
		Vipsender vipsender = new Vipsender();
		vipsender.setCompany(task.getSendCompanyName());
		vipsender.setName(task.getSendName());
		vipsender.setMobile(task.getSendMobile());
		vipsender.setPhone(task.getSendPhone());
		vipsender.setCity(task.getSendProvince()+","+task.getSendCity()+","+task.getSendCounty());
		vipsender.setAddress(task.getSendAddress());
		
		Vipreceiver vipreceiver = new Vipreceiver();
		vipreceiver.setCompany(task.getReceiverCompanyName());
		vipreceiver.setName(task.getReceiverName());
		vipreceiver.setMobile(task.getReceiverMobile());
		vipreceiver.setPhone(task.getReceiverPhone());
		vipreceiver.setCity(task.getReceiverProvince()+","+task.getReceiverCity()+","+task.getReceiverCounty());
		vipreceiver.setAddress(task.getReceiverAddress());
		
		request.setSender(vipsender);
		request.setReceiver(vipreceiver);
		log.info(JSON.toJSONString(request));
		String vip_content = MD5Helper.to64(JSON.toJSONString(request));
		vip_content = vip_content.replaceAll("\\s", "");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String vip_datetime = formatter.format(new Date());
		String vip_style = "json";
		String vip_func = "order.submit";
		String vip_partner = "ligeng";
		String vip_password = "PB0tyHsEfHiFMqux";
		String MD5Str = vip_partner + vip_datetime + vip_func + vip_content + vip_password;
		MD5Str = MD5Str.replaceAll("\\s", "");
		String vip_verify = MD5Helper.ToMD5and32(MD5Str).toLowerCase();
		vipparams.setStyle(vip_style);
		vipparams.setFunc(vip_func);
		vipparams.setPartner(vip_partner);
		vipparams.setDatetime(vip_datetime);
		vipparams.setContent(vip_content);
		vipparams.setVerify(vip_verify);
		return vipparams;
	}


	private Vipparams coverToCFWLRequest(ExpressBO bo) {
		PlExpressApi task = bo.getExpressTask();
		Mailno vipmap = new Mailno();
		if(bo.getZdflag()==true) {
			vipmap.setGetMailno(task.getExternorderkey()+System.currentTimeMillis());
		}else {
			vipmap.setGetMailno(task.getExternorderkey());
		}
		String vip_content = MD5Helper.to64(JSON.toJSONString(vipmap));
		vip_content = vip_content.replaceAll("\\s", "");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String vip_datetime = formatter.format(new Date());//
		String vip_style = "json";
		String vip_partner ="";
		String vip_password ="";
		if("wmwhse4".equals(bo.getWmwsheid())) {
			vip_partner = "ligeng";
			vip_password = "PB0tyHsEfHiFMqux";
		}else if("wmwhse5".equals(bo.getWmwsheid())){
			vip_partner = "lifa";
			vip_password = "F4xNQHeeqtfsaxiwKTWr";
		}
		String vip_func = "order.getMailno";

		String MD5Str = vip_partner + vip_datetime + vip_func + vip_content + vip_password;
		MD5Str = MD5Str.replaceAll("\\s", "");
		String vip_verify = MD5Helper.ToMD5and32(MD5Str);
		Vipparams params = new Vipparams();
		params.setStyle(vip_style);
		params.setFunc(vip_func);
		params.setPartner(vip_partner);
		params.setDatetime(vip_datetime);
		params.setContent(vip_content);
		params.setVerify(vip_verify);
		return params;
	}

	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		// TODO Auto-generated method stub
		
	}
}
